package com.ruoyi.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.simp.user.SimpUser;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.security.Principal;

@Component
public class WebSocketEventListener {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private SimpUserRegistry userRegistry;

    @EventListener
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        // Handle WebSocket connect events
        System.out.println("连接操作..........");
        String simpSessionId = event.getMessage().getHeaders().get("simpSessionId").toString();
        // 查询用户的WebSocketSession
        SimpUser user = userRegistry.getUser(simpSessionId);
        if (user != null) {
           System.out.println(user.getSessions().iterator().next()); // 获取用户的第一个WebSocketSession
            System.out.println("");
        }
        System.out.println(Thread.currentThread().getId());
        System.out.println(event);
    }

    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        // Handle WebSocket disconnect events
        System.out.println("断开连接..........");
        System.out.println(event);
    }
}
